<?php
/**
 * Created by PhpStorm.
 * User: jiangfb
 * Date: 2016/9/22
 * Time: 14:14
 */

namespace common\services\userauth;
use common\entities\myhtsq\ActionEntity;
use common\entities\myhtsq\MyscrmRoleActionEntity;
use common\entities\myhtsq\RoleActionPackageEntity;
use common\repositories\myhtsq\ActionPackageRelationRepository;
use common\repositories\myhtsq\ErpUserRepository;
use common\services\BaseService;
use common\repositories\userauth\UserAuthRepository;
use common\repositories\myhtsq\RoleActionPackageRepository;
use common\repositories\myhtsq\RoleRepository;
use common\repositories\myhtsq\RoleUserRepository;
use common\entities\myhtsq\RoleUserEntity;
use common\repositories\myhtsq\ErpBusinessUnitRepository;
use common\services\myhtsq\ErpInterfaceService;
use yii\helpers\ArrayHelper;

class UserAuthService extends BaseService
{
    public $_userAuthRepository;
    public function __construct(UserAuthRepository $userAuthRepository,$config = [])
    {
        $this->_userAuthRepository = $userAuthRepository;
        parent::__construct($config);
    }

    public function saveRole($data){
        if(empty($data["role_id"])){
            $result = $this->_userAuthRepository->addRole($data);
        }else{
            $result = $this->_userAuthRepository->saveRole($data);
        }

        if ($result === false) {
            self::setAndReturn('-1', '添加或保存角色失败');
        }
        return $result;
    }

    public function deleteRole($role_id)
    {
        $result = $this->_userAuthRepository->deleteRole($role_id);
        if ($result === false){
            self::setAndReturn('-1', '删除角色失败');
        }
        return $result;
    }

    public function getRoleList($keyword)
    {
        $roleList = $this->_userAuthRepository->getRoleList($keyword);
        return $roleData = [['name'=>'集团级角色','field'=>'group','children'=>$roleList['group']],
            ['name'=>'公司级角色','field'=>'company','children'=>$roleList['company']]];
    }

    public function getRoleInfo($role_id)
    {
        $roleInfo = $this->_userAuthRepository->getRoleInfoById($role_id);
        if (empty($roleInfo))
        {
            self::setAndReturn('-1', '获取角色信息失败');
        }
        return $roleInfo;
    }

    public function getAllAuthList()
    {
        return $authList = $this->_userAuthRepository->getAuthList();
    }

    public function getRoleAuthList($role_id)
    {
        $actions = $this->getRoleActionsByRoleID($role_id);
//        /** @var  $rolePockageResp RoleActionPackageRepository */
//        $rolePockageResp = \Yii::createObject(RoleActionPackageRepository::className());
//        $pockageList = $rolePockageResp->getAllRoleActionPackageByRoleId($role_id);
//        foreach ($pockageList as $idx => $package) {
//            $actionsTmp = ActionPackageRelationRepository::getActionsByPackageId($package->action_package_id);
//            if (count($actionsTmp) === 0) {
//                continue;
//            }
//            foreach ($actionsTmp as $idxA => $action) {
//                array_push($actions, $action->action_code);
//            }
//        }
        return ArrayHelper::getColumn($actions, 'action_code');
    }

    public function saveRoleAuth($role_id, $pockage_data)
    {
        /** @var  $roleResp RoleRepository */
        $roleResp = \Yii::createObject(RoleRepository::className());
        $checkRoleResult = $roleResp->checkRoleExit($role_id);
        if (empty($checkRoleResult)){
            self::setAndReturn('-1', '角色不存在');
        }
        /** @var  $roleActionPockageResp RoleActionPackageRepository */
        $roleActionPockageResp = \Yii::createObject(RoleActionPackageRepository::className());
        /** 清缓存 */
        $userList = RoleUserEntity::find()->select('role_user_id,user_id')->where(['role_id'=>$role_id])->asArray()->all();
        foreach($userList as $k => $v){
            \Yii::$app->cache->delete('role_auth_actions_cache_key_'.$v['user_id']);
        }
        return $roleActionPockageResp->saveRoleAuth($role_id,$pockage_data);
    }

    public function getOrgList()
    {
        return $this->_userAuthRepository->getOrgList();
    }

    public function getWaitUser($buGUID, $keyword, $role_id){
        $hasBindUserList = RoleUserEntity::find()
            ->select('myscrm_role_user.user_id,myscrm_erp_user.UserName,myscrm_role_user.role_user_id')
            ->from('myscrm_role_user')
            ->leftJoin('myscrm_erp_user','myscrm_erp_user.UserGUID=user_id')
            ->where(['role_id' => $role_id])
            ->asArray()
            ->all();
        /** @var  $erpUserResp ErpUserRepository */
        $erpUserResp = \Yii::createObject(ErpUserRepository::className());
        $waitUserList = $erpUserResp->getUserListByBuGUIDAndKeyword($buGUID,$keyword,ArrayHelper::getColumn($hasBindUserList,'user_id'));
        return ['hasbingUserList'=>$hasBindUserList, 'waitUserList' => $waitUserList];
    }

    public function getUserListByBuGUIDAndKeyword($buGUID, $keyword)
    {
        /** @var  $erpUserResp ErpUserRepository */
        $erpUserResp = \Yii::createObject(ErpUserRepository::className());

        return $erpUserResp->getUserListByBuGUIDAndKeyword($buGUID, $keyword);
    }

    public function saveRoleUser($role_id, $userList)
    {
        /** @var  $erpUserResp ErpUserRepository */
        $erpUserResp = \Yii::createObject(ErpUserRepository::className());
        return $erpUserResp->saveRoleUserBatch($role_id, $userList);
    }

    public function getUserList($buGUID, $keyword, $perPage, $offset)
    {

        /** @var  $erpUserResp ErpUserRepository */
        $erpUserResp = \Yii::createObject(ErpUserRepository::className());
        /** @var  $roleUserResp RoleUserRepository*/
        $roleUserResp = \Yii::createObject(RoleUserRepository::className());
        $userData = $erpUserResp->getUserList($buGUID,$keyword, $perPage, $offset);
        $userList = $userData['userList'];
        foreach ($userList as $k => $v){
            $userList[$k]['partTimeBUList'] = $this->_userAuthRepository->getPartTimeBUList($v['UserGUID']);
            $roleInfo = $roleUserResp->getRoleNameList($v['UserGUID']);
            $userList[$k]['roleList'] = $roleInfo['roleList'];
            if (in_array(15, $roleInfo['roleIdList'])){
                $userList[$k]['isAreaCharge'] = 1;
            }else{
                $userList[$k]['isAreaCharge'] = 0;
            }
        }
        return ['userList' => $userList, 'pageTotal' => $userData['pageTotal']];
    }

    public function getUserInfo($userGUID)
    {
        /** @var  $erpUserResp ErpUserRepository */
        $erpUserResp = \Yii::createObject(ErpUserRepository::className());
        /** @var  $roleUserResp RoleUserRepository*/
        $roleUserResp = \Yii::createObject(RoleUserRepository::className());
        $userInfo = $erpUserResp->getUserInfo($userGUID);
        $userInfo['partTimeBUList'] = $this->_userAuthRepository->getPartTimeBUList($userInfo['UserGUID']);
        $userInfo['roleList'] = $roleUserResp->getRoleNameList($userInfo['UserGUID'])['roleList'];
        return $userInfo;
    }

    public function setAreaCharge($userGUID)
    {
        /** @var  $roleUserResp RoleUserRepository */
        $roleUserResp = \Yii::createObject(RoleUserRepository::className());
        $result = $roleUserResp->setAreaCharge($userGUID);
        if ($result === false){
            self::setAndReturn('-1', '添加或删除区域负责角色失败失败');
        }
    }

    public function setUserRoleAndBusiness($userGUID, $roleList, $partTimeBUGUIDList)
    {
        $setRoleResult = $this->_userAuthRepository->setUserRole($userGUID, $roleList);
        $setBURetult = $this->_userAuthRepository->setUserParttimeBu($userGUID, $partTimeBUGUIDList);
        if (!$setRoleResult || !$setBURetult){
            self::setAndReturn('-1', '保存失败');
        }
    }

    public function getCurrUserAuthList()
    {
//        if (
//            in_array(\Yii::$app->user->identity->userguid, \Yii::$app->params['allAuthUserId'])
//        ){
//            return ArrayHelper::getColumn(ActionEntity::find()->select('action_id,action_code')->asArray()->all(),'action_code');
//        }
            return $this->_userAuthRepository->getCurrUserAuth();
    }

    public function getRoleActionsByRoleID($role_id)
    {
        return MyscrmRoleActionEntity::find()
            ->select('myscrm_action.action_code,myscrm_role_action.id')
            ->from('myscrm_role_action')
            ->leftJoin('myscrm_action','myscrm_action.action_id=myscrm_role_action.action_id')
            ->where(['myscrm_role_action.role_id'=>$role_id])
            ->asArray()
            ->all();

    }

    public function checkRole($role_id)
    {
        return RoleUserEntity::find()->where(['role_id' => $role_id])->count();
    }

}